from django.shortcuts import render
from rest_framework import viewsets
from rest_framework import mixins
from users.models import GradeStudent
from operation.serializer import GradeStudentSerializer,GradeStudentDetailSerializer,GradeStudentDetailCourseSerializer
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import SessionAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from utils.permission import IsOwnerOrReadOnly
# Create your views here.
from .models import CourseComments
from .serializer import CourseCommentsSerializers,CourseCommentsListSerializers,ExamListSerializers,ExamDetailSerializers
from .serializer import ExamScoreSerializers,SignSerializers,SignUserSerializers
from course.models import PaperList,Paper
from operation.models import UserScore,UserAnswerLog,Sign,SignUser
from datetime import timedelta,datetime
from .serializer import UserAnswerLogSerializers


class StudentsGradeViewSet(mixins.RetrieveModelMixin,mixins.CreateModelMixin,mixins.ListModelMixin,mixins.DestroyModelMixin,viewsets.GenericViewSet):
    """
    create:
        加入班级
    list:
        获取我加入的班级
    delete:
        退出班级
    """

    authentication_classes = (SessionAuthentication,JSONWebTokenAuthentication)
    permission_classes =(IsAuthenticated,IsOwnerOrReadOnly)
    lookup_field = "grade_id"

    def get_queryset(self):
        return GradeStudent.objects.filter(user=self.request.user)

    def get_serializer_class(self):
        if self.action == "create":
            return GradeStudentSerializer
        if self.action == "retrieve":
            return GradeStudentDetailCourseSerializer
        if self.action == "list":
            return GradeStudentDetailSerializer
        return GradeStudentSerializer

    def destroy(self, request, *args, **kwargs):
        if request.user.usertype == "teacher":
            instance = self.get_object()
            self.perform_destroy(instance)
            return Response(status=status.HTTP_204_NO_CONTENT)
        else:
            return Response(status=status.HTTP_404_NOT_FOUND,data={"non_field_errors":"只有老师才具有退出班级功能"})


class CourseCommentsViewSet(mixins.ListModelMixin,mixins.CreateModelMixin,viewsets.GenericViewSet):
    """
    list:
    获取用户评论

    create:
    添加用户评论
    """
    queryset = CourseComments.objects.all()
    permission_classes = (IsAuthenticated,IsOwnerOrReadOnly)
    authentication_classes = (SessionAuthentication,JSONWebTokenAuthentication)

    def get_serializer_class(self):
        if self.action == "list":
            return CourseCommentsListSerializers
        else:
            return CourseCommentsSerializers

    def get_queryset(self):
        if self.request.query_params.get("courseid"):
            return CourseComments.objects.filter(course=self.request.query_params.get("courseid"))
        else:
            return CourseComments.objects.all()


class ExamListViewSet(mixins.ListModelMixin,mixins.RetrieveModelMixin,viewsets.GenericViewSet):
    """
    list:
       获取用户考试
    retrieve:
       获取用户考试详情

    """
    permission_classes = (IsAuthenticated,)
    authentication_classes = (SessionAuthentication,JSONWebTokenAuthentication)

    def get_queryset(self):
        courses = []
        p = UserScore.objects.filter(user=self.request.user).values_list("paper")
        for i in self.request.user.grades.all():
            courses.extend(i.grade.course.all())
        return PaperList.objects.filter(course__in=courses).exclude(id__in=p)

    serializer_class = ExamListSerializers

    def get_serializer_class(self):
        if self.action == "list":
            return ExamListSerializers
        if self.action == "retrieve":
            return ExamDetailSerializers

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        if not instance.is_allow:
            return Response({"detail":"考试暂未开启"},status=status.HTTP_404_NOT_FOUND)
        if UserScore.objects.filter(paper=instance,user=request.user):
            return Response({"detail": "已考过"}, status=status.HTTP_404_NOT_FOUND)
        serializer = self.get_serializer(instance)
        return Response(serializer.data)


class UserScoreViewSet(mixins.CreateModelMixin,viewsets.GenericViewSet):
    """
    create:
       创建用户成绩记录
    """
    permission_classes = (IsAuthenticated,)
    authentication_classes = (SessionAuthentication,JSONWebTokenAuthentication)
    serializer_class = ExamScoreSerializers

    def create(self, request, *args, **kwargs):
        data = request.data
        sum_score = data.get("sum")
        answer = data.get("answer")
        score = data.get("score")
        exam_id = data.get("exam_id")
        papers = data.get("papers")
        course_id = data.get("course_id")
        papers_dict = {i.question.id:i for i in Paper.objects.filter(course_id=course_id,paper_name_id=exam_id)}
        c = UserScore.objects.filter(paper_id=exam_id,user=request.user)
        if c:
            return Response({"detail":"用户已考过"}, status=status.HTTP_404_NOT_FOUND)
        user_score = UserScore(user=request.user,paper_id=exam_id,total=score,sumcore=sum_score)
        user_score.save()
        orm_list = [UserAnswerLog(user=request.user,course_id=course_id,paper_id=papers_dict.get(int(key)).id,answer=answer.get(key) or "",score=value.get("userscore")) for key,value in papers.items()]
        UserAnswerLog.objects.bulk_create(orm_list)
        return Response({"detail":"提交成功"}, status=status.HTTP_201_CREATED)


class SignViewSet(mixins.ListModelMixin,mixins.CreateModelMixin,viewsets.GenericViewSet):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (SessionAuthentication,JSONWebTokenAuthentication)

    def get_queryset(self):
        if self.action == "create":
            return SignUser.objects.filter(students=self.request.user)
        return Sign.objects.filter(grade_id__in=self.request.user.grades.all().values_list("grade"),add_time__gte=datetime.now() - timedelta(minutes=10)).exclude(id__in=SignUser.objects.filter(students=self.request.user).values_list("sign"))

    def get_serializer_class(self):
        if self.action == "create":
            return SignUserSerializers
        else:
            return SignSerializers


class UserAnswerLogViewSet(mixins.ListModelMixin,viewsets.GenericViewSet):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (SessionAuthentication,JSONWebTokenAuthentication)

    serializer_class = UserAnswerLogSerializers

    def get_queryset(self):
        params = self.request.query_params.dict()
        paper_id = params.get("paperid")
        if paper_id:
            return UserAnswerLog.objects.filter(user=self.request.user,paper__paper_name_id=paper_id)
        else:
            return []
